"""
日志工具 - 用于规整地打印AI响应和程序状态
"""

import json
from datetime import datetime


class ResponseLogger:
    def __init__(self, log_file="ai_responses.log"):
        self.log_file = log_file

    def log_response(self, program_path, prompt, response, seeds_generated):
        """记录完整的AI响应"""
        timestamp = datetime.now().isoformat()

        log_entry = {
            "timestamp": timestamp,
            "program": program_path,
            "prompt_length": len(prompt),
            "response_length": len(response),
            "seeds_generated": seeds_generated,
            "prompt_preview": prompt[:500] + "..." if len(prompt) > 500 else prompt,
            "full_response": response
        }

        # 打印到控制台
        self._print_to_console(log_entry)

        # 保存到文件
        self._save_to_file(log_entry)

    def _print_to_console(self, log_entry):
        """规整地打印到控制台"""
        print("\n" + "=" * 80)
        print(" AI 响应详情")
        print("=" * 80)
        print(f" 时间: {log_entry['timestamp']}")
        print(f" 程序: {log_entry['program']}")
        print(f" 统计: 提示词{log_entry['prompt_length']}字符, "
              f"响应{log_entry['response_length']}字符, "
              f"生成{log_entry['seeds_generated']}个种子")
        print("-" * 80)
        print(" AI 完整响应:")
        print("-" * 80)
        print(log_entry['full_response'])
        print("=" * 80)
        print("\n")

    def _save_to_file(self, log_entry):
        """保存到日志文件"""
        try:
            with open(self.log_file, 'a', encoding='utf-8') as f:
                f.write(json.dumps(log_entry, ensure_ascii=False, indent=2))
                f.write("\n" + "=" * 80 + "\n")
        except Exception as e:
            print(f" 保存日志失败: {e}")


def setup_logging():
    """设置日志"""
    return ResponseLogger()